package com.elastic.test.high_level_client;

import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.apache.http.message.BasicHeader;
import org.elasticsearch.client.Node;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;

/**
 * @author: 李德才
 * @TODO 构建链接
 * @description:
 * @create: 2021-04-11 11:06
 **/
public class ClientBuilders {

    private static final String CLUSTER_HOSTNAME_PORT = "192.168.31.100:9200";


    public static RestClientBuilder getClientBuilder() {
        String[] hostNamesPort = CLUSTER_HOSTNAME_PORT.split(",");
        if (hostNamesPort.length == 0) {
            throw new NullPointerException("没有获取到 Elasticsearch 可用地址");
        }
        RestClientBuilder restClientBuilder = null;
        for (String hostPort : hostNamesPort) {
            String[] split = hostPort.split(":");
            restClientBuilder = RestClient.builder(new HttpHost(split[0].trim(), Integer.parseInt(split[0].trim()), "http"));
        }
        /** RestClientBuilder 在构建 RestClient 实例时可以设置以下的可选配置参数 */
        Header[] headers = new Header[]{new BasicHeader("header", "application/json")};
        restClientBuilder.setDefaultHeaders(headers);

        /** 设置每次节点发生故障时收到通知的侦听器。内部嗅探到故障时被启用。*/
        restClientBuilder.setFailureListener(new RestClient.FailureListener() {
            @Override
            public void onFailure(Node node) {
                super.onFailure(node);
            }
        });
        /** 设置修改默认请求配置的回调（例如：请求超时，认证，或者其他设置）。 */
        restClientBuilder.setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder.setSocketTimeout(1000));


        /** 设置身份认证 */
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "elastic"));


        restClientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
            @Override
            public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {
                httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
//                线程设置
                httpAsyncClientBuilder.setDefaultIOReactorConfig(IOReactorConfig.custom().setIoThreadCount(10).build());
                return httpAsyncClientBuilder;
            }
        });

        return restClientBuilder;
    }

}
